package com.gla.market.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gla.market.R;
import com.gla.market.adapter.OrderShopAdapter;
import com.gla.market.constant.Constants;
import com.gla.market.entity.AddressItem;
import com.gla.market.entity.Order;
import com.gla.market.entity.OrderDetail;
import com.gla.market.entity.OrderRequest;
import com.gla.market.entity.OrderStateEnum;
import com.gla.market.entity.ShopCart;
import com.gla.market.entity.ShopInCart;
import com.gla.market.utils.NetUtil;
import com.gla.market.utils.SharedPreferencesUtil;

import java.io.IOException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;


public class OrderActivity extends AppCompatActivity {

    private static final String POP = "com.gla.market.popwindow";
    private static final String PAY = "com.gla.market.poppaywindow";
    private static final Integer ALI_PAY = 0;
    private static final Integer WECHAT_PAY = 1;
    private Integer payMethod = ALI_PAY;
    private OrderShopAdapter orderShopAdapter;
    private ArrayList<ShopInCart> shopBeanList;
    private Integer user_id;
    private AddressItem address;
    private ArrayList<Integer> orderIdList = new ArrayList<>();
    //控件
    private RecyclerView listView;  //商品列表
    private CheckBox wechatpay;
    private CheckBox alipay;
    private TextView tv_price;
    private Button bt_submit;
    //地址控件
    private TextView address_title;
    private TextView address_people;
    private TextView address_tel;
    //广播接收器
    private OrderReceiver orderReceiver;
    private IntentFilter intentFilter;

    private Context mContext;

    private Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case -2:
                    //未登录，需要登录！
                    Toast.makeText(mContext, "您还未登录！请先登录！", Toast.LENGTH_SHORT).show();
                    break;
                case -1:
                    //网络请求失败
                    Toast.makeText(mContext, "网络请求失败！"
                            , Toast.LENGTH_SHORT).show();
                    break;
                case 0:
                    Toast.makeText(mContext, "出现错误！", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    //弹出支付界面
                    popPayWnd();
                    break;
                case 2:
                    showMoney();
                    finish();
                    break;
                case 3:
                    Toast.makeText(mContext,"订单中有商品库存不足，提交失败!",Toast.LENGTH_SHORT).show();
                    finish();
                case 4:
                    //显示提交按钮
                    bt_submit.setVisibility(View.VISIBLE);
                    //修改地址栏
                    address_people.setText(address.getGetman());
                    address_tel.setText(address.getPhone());
                    address_title.setText(address.getArea()+address.getName());
                    break;
                case 5:
                    double money = (int)msg.obj;
                    Toast.makeText(mContext, "支付成功!余额:"+money + "元", Toast.LENGTH_SHORT).show();
                    break;
                case 6:
                    Toast.makeText(mContext, "支付失败!"+msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }

        }
    };

    public void showMoney() {
        String url = Constants.BASE_URL + Constants.GET_USER_MONEY+"/"+user_id;
        NetUtil.doGet(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(mContext, "请求失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string().trim();
                JSONObject object = JSON.parseObject(result);
                Message message = Message.obtain();
                System.out.println(object);
                if (!object.getString("message").contains("JWT") && object.getString("error")==null && object.getInteger("code")==100) {
                    message.what = 5;
                    message.obj = object.getInteger("data");
                } else {
                    message.what = 6;
                    message.obj = object.getString("message");
                }
                uiHandler.sendMessage(message);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);
        mContext = this;
        Intent intent = getIntent();
        shopBeanList = (ArrayList<ShopInCart>) intent.getSerializableExtra("list");
        //初始化控件
        initView();
        intentFilter = new IntentFilter();
        intentFilter.addAction(POP);
        orderReceiver = new OrderReceiver();
        registerReceiver(orderReceiver,intentFilter);

        user_id = (Integer) SharedPreferencesUtil.get(this,"userInfo","user_id",1);
        setAddress();

    }

    private void setAddress() {
        String url = Constants.BASE_URL + Constants.GET_DEFALUT_ADDRESS +"?user_id="+ user_id;
        NetUtil.doGet(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                uiHandler.sendEmptyMessage(-1);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string().trim();
                JSONObject object = JSON.parseObject(result);
                Message message = Message.obtain();
                System.out.println("获取到默认地址："+object);
                if (object.getString("error") == null && object.getInteger("code") == 100) {
                    address = object.getObject("data",AddressItem.class);
                    message.what = 4;
                }
                uiHandler.sendMessage(message);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(orderReceiver);
    }
    private void initView(){
        listView = findViewById(R.id.order_list);
        orderShopAdapter = new OrderShopAdapter(this);
        orderShopAdapter.setShopBeanList(shopBeanList);
        listView.setLayoutManager(new LinearLayoutManager(this));
        listView.setAdapter(orderShopAdapter);
        listView.addItemDecoration(new SpaceItemDecoration(20));
        wechatpay = findViewById(R.id.btn_wechatpay);
        alipay = findViewById(R.id.btn_alipay);
        alipay.setChecked(true);
        tv_price = findViewById(R.id.order_foot_price);
        bt_submit = findViewById(R.id.submit_button);
        //在获取到地址前先隐藏
        bt_submit.setVisibility(View.GONE);
        address_title = findViewById(R.id.order_address_title);
        address_people = findViewById(R.id.order_address_people);
        address_tel = findViewById(R.id.order_address_tel);

        double price = 0;
        for(ShopInCart shop : shopBeanList){
            for(ShopCart item : shop.getList()){
                price += item.getCommodity().getPrice() * item.getNumber();
            }
        }
        //保留两位小数
        DecimalFormat df = new DecimalFormat("0.00");
        String str = df.format(price);
        tv_price.setText("￥"+str);
        bt_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                submit();

                bt_submit.setClickable(false);
            }
        });
    }

    //返回按钮响应
    public void back(View view) {
        finish();
    }

    //提交按钮响应
    public void submit() {
        //所有店铺订单集合
        List<OrderRequest> requestList = new ArrayList<>();
        //不同店铺另起不同订单
        for(int i = 0;i<shopBeanList.size();i++) {

            //---------创建Order信息-------------
            Order orderInfo = new Order(null,null, Order.PLACED,address.getArea(),user_id,shopBeanList.get(i).getRemarks());
            //---------创建订单详情请求-------------
            List<OrderDetail> detailList = new ArrayList<>();
            for (ShopCart item : shopBeanList.get(i).getList()) {
                OrderDetail orderItem = new OrderDetail(
                        null, item.getNumber(), null, null,
                        item.getCommodity().getId());
                detailList.add(orderItem);
            }
            //---------创建OrderRequest-----------
            OrderRequest requestListItem = new OrderRequest(orderInfo,detailList);
            requestList.add(requestListItem);
        }
        //发送创建订单请求
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), JSON.toJSONString(requestList));
        String url = Constants.BASE_URL + Constants.POST_INSERT_ORDER;
        NetUtil.doPost(url, body, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                uiHandler.sendEmptyMessage(-1);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string().trim();
                JSONObject object = JSON.parseObject(result);
                Message message = Message.obtain();
                System.out.println("点提交订单结果:"+object);
                if (object.getString("error") == null && object.getInteger("code") == 100) {
                    //下单成功
                    message.what = 1;
                    JSONArray idList = object.getJSONArray("data");
                    for(int i=0;i<idList.size();i++){
                        orderIdList.add(idList.getInteger(i));
                    }
                } else if(object.getInteger("code") == 101 && object.getString("message").equals("订单中有商品库存不足，失败")){
                    //商品库存不足
                    message.what = 3;
                }
                uiHandler.sendMessage(message);
            }
        });

    }

    public void popPayWnd(){
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.order_pay_pop_window, null);
        PopupWindow popWindow = new PopupWindow (contentView, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
        //设置可获取焦点
        popWindow.setFocusable(true);
        //设置可点击弹窗外内容
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        popWindow.setOutsideTouchable(true);
        //设置关闭处关闭弹窗
        contentView.findViewById(R.id.pay_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bt_submit.setText("已取消支付");
                popWindow.dismiss();
            }
        });

        //支付按钮
        Button bt_submit = contentView.findViewById(R.id.pay_submit);
        bt_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pay();
                popWindow.dismiss();
            }
        });
        popWindow.showAtLocation(findViewById(R.id.root), Gravity.BOTTOM, 0,0);
    }

    //提交支付
    public void pay(){

        for(Integer id : orderIdList){
            String url = Constants.BASE_URL + Constants.GET_CHANGE_ORDER_STATE + "?order_id=" +id+"&state="+Order.PAID;
            NetUtil.doGet(url, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    uiHandler.sendEmptyMessage(-1);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String result = response.body().string().trim();
                    JSONObject object = JSON.parseObject(result);
                    Message message = Message.obtain();
                    System.out.println(object);
                    if (object.getString("error") == null && object.getInteger("code") == 100) {
                        message.what = 2;
                    }
                    uiHandler.sendMessage(message);
                }
            });
        }
    }

    //选择支付方式响应
    public void checkPayMethod(View view) {
        if(view.getId() == R.id.btn_alipay){
            wechatpay.setChecked(!alipay.isChecked());
        } else if(view.getId() == R.id.btn_wechatpay){
            alipay.setChecked(!wechatpay.isChecked());
        }
        payMethod = wechatpay.isChecked() ? WECHAT_PAY : ALI_PAY;
    }

    //需改地址响应
    public void editAddress(View view) {
        Toast.makeText(this,"选择地址",Toast.LENGTH_SHORT).show();
    }

    class OrderReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(POP)){
                Integer shop_id = intent.getIntExtra("shop_id", -1);
                View contentView = LayoutInflater.from(context).inflate(R.layout.order_remark_pop_window, null);
                PopupWindow popWindow = new PopupWindow (contentView, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
                //设置可获取焦点
                popWindow.setFocusable(true);
                //设置可点击弹窗外内容
                popWindow.setBackgroundDrawable(new BitmapDrawable());
                popWindow.setOutsideTouchable(true);
                //设置关闭处关闭弹窗
                contentView.findViewById(R.id.remarks_close).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        popWindow.dismiss();
                    }
                });
                //输入框
                EditText edit = contentView.findViewById(R.id.remarks_text);
                for(int i=0;i<shopBeanList.size();i++){
                    if(shop_id.equals(shopBeanList.get(i).getId())){
                        edit.setText(shopBeanList.get(i).getRemarks());
                    }
                }
                //提交按钮
                Button bt_submit = contentView.findViewById(R.id.remarks_submit);
                bt_submit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        for(int i=0;i<shopBeanList.size();i++){
                            if(shop_id.equals(shopBeanList.get(i).getId())){
                                shopBeanList.get(i).setRemarks(edit.getText().toString());
                                orderShopAdapter.notifyItemChanged(i);
                                popWindow.dismiss();
                            }
                        }
                    }
                });
                popWindow.showAtLocation(findViewById(R.id.root), Gravity.BOTTOM, 0,0);
            }
            else if(intent.getAction().equals(PAY)){
                View contentView = LayoutInflater.from(context).inflate(R.layout.order_pay_pop_window, null);
                PopupWindow popWindow = new PopupWindow (contentView, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
                //设置可获取焦点
                popWindow.setFocusable(true);
                //设置可点击弹窗外内容
                popWindow.setBackgroundDrawable(new BitmapDrawable());
                popWindow.setOutsideTouchable(true);
                //设置关闭处关闭弹窗
                contentView.findViewById(R.id.remarks_close).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        popWindow.dismiss();
                    }
                });

                //支付按钮
                Button bt_submit = contentView.findViewById(R.id.remarks_submit);
                bt_submit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        popWindow.dismiss();
                    }
                });
                popWindow.showAtLocation(findViewById(R.id.root), Gravity.BOTTOM, 0,0);
            }
        }
    }

    //修改RecyclerView Item间隔的辅助类
    class SpaceItemDecoration extends RecyclerView.ItemDecoration {
        int mSpace;
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            outRect.bottom = mSpace;
            if (parent.getChildAdapterPosition(view) == 0) {
                outRect.top = mSpace/2;
            }
            outRect.left = outRect.right = 15;
        }

        public SpaceItemDecoration(int space) {
            this.mSpace = space;
        }
    }


}